package store.lunangangster.nodeflow.rt.element.flow;

import static store.lunangangster.nodeflow.enums.FlowType.FLOW_FOR;

import cn.hutool.core.collection.CollUtil;
import store.lunangangster.nodeflow.enums.FlowType;
import store.lunangangster.nodeflow.rt.DataBus;
import store.lunangangster.nodeflow.rt.element.Node;

/**
 * For循环执行流
 *
 * @author cwk
 * @version 1.0
 */
public class ForFlow extends LoopFlow {

	private Node forNode;

	@Override
	public void execute(Integer slotIndex) {
		try {
			forNode.execute(slotIndex);
			int loopTimes = (int) DataBus.getSlot(slotIndex).getData(forNode.getNodeComponent().getLoopTimesKey());
			if (!CollUtil.isEmpty(this.executableList)) {
				for (int i = 0; i < loopTimes ; i++) {
					this.executableList.forEach(executable -> executable.execute(slotIndex));
					if (exit(slotIndex)) {
						break;
					}
				}
			}
		} finally {
			forNode.getNodeComponent().removeLoopTimesKey();
		}
	}

	@Override
	public FlowType getFlowType() {
		return FLOW_FOR;
	}

	public Node getLoopNode() {
		return forNode;
	}

	public void setLoopNode(Node forNode) {
		this.forNode = forNode;
	}
}
